﻿using Drive.LiveChat.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Drive.Support.Extensions;
using Drive.LiveExcelHost.Mvc;
using Drive.LiveChat.Server.Models;
using System.Net;
using Newtonsoft.Json.Linq;

namespace Drive.LiveExcelHost.Controllers
{
    public class AgentChatController : Controller
    {
        [Services.Path("/app/conversation/send")]
        public object AgentSend(long convId, string content, long t)
        {
            var conv = GetConversation(convId, true, content);
            var message = db.ChatMessages.Add(new LiveChat.Model.ChatMessage
            {
                AgentId = 0,
                Content = content,
                ContentType = "text",
                SendBy = "agent",
                SendTime = DateTime.Now,
                VisitorId = conv.VisitorId,
                ConvId = conv.Id
            });
            db.SaveChanges();
            RedisPubSub.Publish($"visitor_{conv.VisitorId}", TypedMessage.CreateMessageFromAgent(message.Entity, conv));
            return message.Entity;
        }

        public Conversation GetConversation(long id, bool isAgent, string content)
        {
            var conv = db.Conversations.Find(id);
            if (conv == null || conv.EndTime < DateTime.Now)
            {
                throw new Exception("err_invalid_conv");
            }
            else
            {
                if (isAgent)
                {
                    conv.AgentSendQty = conv.AgentSendQty + 1;
                    conv.AgentLastSendTime = DateTime.Now;
                    conv.UpdateTime = DateTime.Now;
                    conv.LastSendBy = "agent";
                    conv.LastSendContent = content;
                }
                else
                {
                    conv.VisitorSendQty = conv.VisitorSendQty + 1;
                    conv.VisitorLastSendTime = DateTime.Now;
                    conv.UpdateTime = DateTime.Now;
                    conv.LastSendBy = "visitor";
                    conv.LastSendContent = content;
                }
                var ra = db.SaveChanges();
            }
            return conv;
        }

        [Services.Path("/app/conversation/get")]
        public object GetConversation(long id)
        {
            return db.Conversations.Find(id);
        }

        [Services.Path("/app/conversation/messages")]
        public object GetMessages(long convId, int page, int size)
        {
            return db.ChatMessages.Where(x => x.ConvId == convId)
                .OrderByDescending(x => x.Id)
                .ToPagedList(page, size)
                .OrderBy(x => x.Id);
        }

        [Services.Path("/app/login")]
        public object Login(AgentLogin login)
        {
            var visitor = new VisitorInfo { VisitorId = 0, isAgent = true };
            var uid = SocketIoBootstrapper.EncodeVisitorInfo(visitor);
            //Response.Cookies.Add(new Cookie("agent_uid", uid, "/") { HttpOnly = false });
            return new { agent_uid = uid };
        }
        [Services.Path("/app/conversations")]
        public object GetConversations()
        {
            return db.Conversations.ToList();
        }
        public object GetChatSessions(long agentId, int page, int size)
        {
            using (var db = new ChatDbContext().AsNoTracking())
            {
                return db.Conversations.Where(x => x.AgentId == agentId).ToPagedList(page, size);
            }
        }

        internal void HandleAgentMessage(int agentId, int v, string content)
        {
            throw new NotImplementedException();
        }

        public object EndChatSession(int id, int endByAgentId, string endReason)
        {
            using (var db = new ChatDbContext())
            {
                var item = db.Conversations.Find(id);
                if (item.EndTime == null)
                {
                    throw new Exception("err_chat_session_already_end");
                }
                item.EndByAgentId = endByAgentId;
                item.EndReason = endReason;
                item.EndTime = DateTime.Now;
                db.SaveChanges();
                return item;
            }
        }

        public Conversation GetConversation(long visitorId, long cnovId)
        {
            using (var db = new ChatDbContext())
            {
                var item = db.Visitors.Find(visitorId);
                if (item == null)
                {
                    throw new Exception("err_invalid_item");
                }
                var s = db.Conversations.Find(cnovId);
                if (s == null)
                {
                    throw new Exception("err_invalid_item");
                }
                if (s.VisitorId != visitorId)
                {
                    throw new Exception("err_invalid_request");
                }
                if (s.EndTime != null)
                {
                    //已关闭
                    return null;
                }
                return s;
            }
        }
    }
}
